package net.wxxr.http.engine;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.wxxr.http.config.HttpContans;
import net.wxxr.http.config.ResponseHeaderConfig;
import net.wxxr.http.model.pojo.HttpResult;
import net.wxxr.http.request.HttpBaseRequest;
import net.wxxr.http.request.HttpPostRequest;
import oauth.signpost.http.HttpParameters;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.Header;
import org.apache.http.entity.mime.MinimalField;



public class HttpPostEngine extends HttpInIdempotentEngine {
   
	
    
	public HttpPostEngine(HttpBaseRequest request) {
		super(request);
	}

	@Override
	protected void initTag() {
		TAG = "HttpPostEngine";
	}

	
	@Override
	protected void setRequestParams() throws UnsupportedEncodingException {
		
		AbstractHttpEntity entity = null;
		HttpPostRequest postRequest = (HttpPostRequest)baseRequest;
		String contentType = postRequest.getContentType();
		String entityString = null;
		if(HttpContans.CONTENT_TYPE_JSON.equals(contentType)){
			entityString = postRequest.getBodyData();
		}else if(HttpContans.CONTENT_TYPE_XML.equals(contentType)){
			
		}else if(HttpContans.CONTENT_TYPE_MAP.equals(contentType)){
			entityString = map2KeyValueString(postRequest.getBodyParams());
		}
		
		if(null != entityString){
			entity = new StringEntity(entityString,HttpContans.CHARSET_GBK);
			//服务器告诉浏览器自己响应的对象的类型
			if(null != contentType){
				if(HttpContans.CONTENT_TYPE_JSON.equals(contentType)){
					//发送的参数文本格式为json格式
					entity.setContentType("application/json");
				}else if(HttpContans.CONTENT_TYPE_XML.equals(contentType)){
					//发送的参数文本格式为xml格式
					entity.setContentType("application/xml");
				}else{
					//发送的参数文本格式为?name=value&name2=value2&name3=value3格式
					entity.setContentType("application/x-www-form-urlencoded");
				}
			}
		}
		
		
		
		
		if(null != entity){
			((HttpPost) requestBase).setEntity(entity);
		}
    	
    	
	}
	
	private String map2KeyValueString(HttpParameters map) {
		if (map == null) {
			return "";
		}
		StringBuffer str = new StringBuffer("");
		Set<String> keySet = map.keySet();
		Iterator<String> it = keySet.iterator();
		while (it.hasNext()) {
			String key = it.next();
			String value = map.getAsQueryString(key);
			str.append(value + "&");
		}
		if (str.length() > 0) {
			str = str.deleteCharAt(str.length() - 1);
		}
		return str.toString();

	}
	
}
